package javaStudy.反射;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/*
获取成员变量，并对其赋值
 */
public class Demo1 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<Student> studentClass = Student.class;
        //获取student的所有公有成员变量，并返回一个数组
        Field[] fields = studentClass.getFields();
        //获取student的所有成员变量，包括私有，并返回一个数组
        Field[] declaredFields = studentClass.getDeclaredFields();
        //获取单个公有成员变量
        Field ageField = studentClass.getField("age");
        //获取单个成员变量
        Field nameField = studentClass.getDeclaredField("name");
        Field idField = studentClass.getDeclaredField("id");
        //获取无参构造，生成对象
        Constructor<Student> constructor = studentClass.getConstructor();
        Student student = constructor.newInstance();

        //调用Field的set方法，给student公有的成员变量age赋值
        ageField.set(student,20);
        System.out.println(student);

        //给私有或者默认成员变量赋值
        idField.setAccessible(true);
        nameField.setAccessible(true);
        idField.set(student,"602022");
        nameField.set(student,"zhulei");
        System.out.println(student);


    }
}
